package com.sportizz.model;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Instances;
import android.provider.CalendarContract.Reminders;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.sportizz.sport.Custom_dialog_class;
import com.sportizz.sport.DatabaseAdapter;
import com.sportizz.sport.MainActivity;
import com.sportizz.sport.Setting_Act;
import com.sportizz.sport.StartActivity;
import com.sportizz.sport.Utils;

@SuppressLint("DefaultLocale")
public class PlayerData {

	private final List<Player> players = new ArrayList<Player>();
	private final List<Menu_champ_A> menu_champ = new ArrayList<Menu_champ_A>();

	Activity act;
	public static Context con;
	public String country_code = null;
	public String player_code = null;
	public String is_team = null;
	
	public String sport_list_final = null;
	public String current_date = null;
	public String hour = null;
	String player_name = null;

	public ProgressDialog pDialog;
	public String search_rss = null;
	public boolean Check_tab = false;
	String Json_result = null;
	String cs_code_selected;
	public String team_code, code_sp;

	public boolean Check_player;
	public boolean Check_team;
	public boolean Check_champ;
	public boolean i_foll, all_sport, search, tablet, up_y_team;
	public String champ_list_final,player_list_final;
	
	ArrayList<String> player_list;
	ArrayList<String> champ_list;

	public DatabaseAdapter dataAdapter;

	@SuppressWarnings("deprecation")
	@SuppressLint({ "NewApi", "SimpleDateFormat" })
	public PlayerData(Context _context, String P_Name, String _country_code,
			String player_code, String cs_code_selected, String team_code,
			String is_team,String player_list_final, String champ_list_final,ArrayList<String> cp_list, ArrayList<String> pl_list, String sport_list,
			boolean i_foll, boolean all_sport, boolean search, boolean tablet,
			String current_date, final String hour, String code_sp,
			boolean up_y_team) {

		dataAdapter = new DatabaseAdapter(_context);

		this.con=_context;
		act = (Activity) _context;
		this.country_code = _country_code;
		this.player_code = player_code;

		this.cs_code_selected = cs_code_selected;
		this.team_code = team_code;
		this.is_team = is_team;
		this.player_name = P_Name;
		this.player_list = cp_list;
		this.champ_list = pl_list;
		this.sport_list_final = sport_list;
		
		this.champ_list_final=champ_list_final;
		this.player_list_final =player_list_final;
		
		this.i_foll = i_foll;
		this.all_sport = all_sport;
		this.search = search;
		this.current_date = current_date;
		this.hour = hour;
		this.tablet = tablet;
		this.code_sp = code_sp;
		this.up_y_team = up_y_team;

		if (player_code == null && i_foll == false && all_sport == true
				&& current_date == null && hour == null && search == false
				&& country_code != null) {
			Log.d("suraj", "All Sport = ");
			Json_result = Utils.readJsonFeed(
					"http://www.sportizza.com/interface/ios_all_sport.php?iso_cd="
							+ country_code, act);
			// Json_result =
			// Utils.readJsonFeed("http://www.sportizza.com/interface/ios_all_follow.php?iso_cd=in&follow=2049&follow_cs=102",act);

		}


		if (cs_code_selected != null && country_code != null
				&& current_date == null
				&& team_code == null && hour == null) {
			Log.d("suraj", "Upcoming Browser");

			Json_result = Utils
					.readJsonFeed(
							"http://sportizza.com/interface/ios_matches_for_cs.php?cs_code="
									+ cs_code_selected + "&iso_cd="
									+ country_code + "", act);
		}

		if (cs_code_selected == null && country_code != null
				&& current_date == null && team_code != null && hour == null) {
			Log.d("suraj", "Upcoming team Browser");
			Json_result = Utils.readJsonFeed(
					"http://sportizza.com/interface/ios_matches_for_teams.php?team_code"
							+ team_code + "&iso_cd=" + country_code + "", act);
		}

		if (current_date != null && hour != null) {
			Log.d("suraj", "Upcoming ");
			// Json_result =
			// Utils.readJsonFeed("http://sportizza.com/interface/ios_next.php?next_hr=24&dt_time=201311251430&iso_cd=in",act);
			Json_result = Utils.readJsonFeed(
					"http://sportizza.com/interface/ios_next.php?next_hr="
							+ hour + "&dt_time=" + current_date + "&iso_cd="
							+ country_code + "", act);

			Log.d("suraj",
					"http://sportizza.com/interface/ios_next.php?next_hr="
							+ hour + "&dt_time=" + current_date + "&iso_cd="
							+ country_code);
		}

		if (player_code != null && search == true && i_foll == false
				&& all_sport == false) {

			if (is_team.equals("N") || is_team.equals("Y")) {
				Json_result = Utils.readJsonFeed(
						"http://sportizza.com/interface/ios_follow_Search.php?iso_cd="
								+ country_code + "&follow=" + player_code
								+ "&follow_cs=-1", act);
				Log.d("suraj",
						"http://sportizza.com/interface/ios_follow_Search.php?iso_cd="
								+ country_code + "&follow=" + player_code
								+ "&follow_cs=-1");
			} else if (is_team.equals("A")) {
				Json_result = Utils.readJsonFeed(
						"http://sportizza.com/interface/ios_follow_Search.php?iso_cd="
								+ country_code + "&follow=-1&follow_cs="
								+ player_code + "", act);
				Log.d("suraj",
						"http://sportizza.com/interface/ios_follow_Search.php?iso_cd="
								+ country_code + "&follow=-1&follow_cs="
								+ player_code);
			}
		}


		Check_tab = isTablet(_context);

		Log.d("suraj", "Table = " + Check_tab);

		if (Json_result.equals("null")
				&& (i_foll == false && all_sport == false && search == true)
				&& (current_date == null || hour == null)) {
			Log.d("suraj", "Json Null");

			final Custom_dialog_class custom_dialog = new Custom_dialog_class(
					act, player_name, false, null, false);
			custom_dialog.show();

			final Timer t = new Timer();
			t.schedule(new TimerTask() {
				public void run() {
					custom_dialog.dismiss();
					t.cancel();
					// return ;
				}
			}, 5000);
		}

		if (i_foll == true && Json_result == null) {
			String json_ss = Json_result.substring(0, 4);

			Log.d("suraj",
					json_ss + "==Json Json_result ==" + json_ss.equals("null"));

			if (json_ss.equals("null")) {
				Json_result = "null";
			}
		}
		
		Log.d("suraj", "Json "+Json_result);
		
		if (Json_result.equals("null") || Json_result == null) {
			Log.d("suraj", "Json Null");
//			new Thread(new Runnable() {
//				@Override
//				public void run() {
//					act.runOnUiThread(new Runnable() {
//						public void run() {
//							final Custom_dialog_class custom_dialog = new Custom_dialog_class(
//									act, null, true, null, false);
//							custom_dialog.show();
//
//							final Timer t1 = new Timer();
//							t1.schedule(new TimerTask() {
//								public void run() {
//									custom_dialog.dismiss();
//									t1.cancel();
//									// return ;
//								}
//							}, 3000);
//						}
//					});
//				}
//			}).start();
			MainActivity.playerAdaptersize=0;
			return;
		} else { 
			Log.i("suraj_", "code_sp = " + code_sp);

			Log.d("suraj", "Json Not Null");
			try {

				// Log.d("suraj", "String result=" + Json_result);

				String champ_details = null, new_champ = null, new_date = null;
				String champ_channel_list = null;

				String i_follow_data = null;

				JSONArray array = new JSONArray(Json_result);

				// Log.d("suraj", "String result=" + Json_result);
				int array_len = array.length();

				List<String> new_json_cs = new ArrayList<String>();
				int count = 0;

				
				
				for (int i = 0; i < array_len; i++) {

					JSONObject JsonObject = array.getJSONObject(i);

					// Log.e("suraj", "Inside For.."+JsonObject);

					// Log.v("suraj", "Inside For.."+game_txt);

					String ss_cs_code = JsonObject.getString("ss_cs_code");

					String ss_cs_name = JsonObject.getString("ss_cs_name")
							.toUpperCase();

					Log.v("suraj", "" + ss_cs_name);

					// String player_header_name = JsonObject
					// .getString("player_header_name");

					String ss_sport = JsonObject.getString("ss_sport");

					Log.e("suraj", "" + ss_sport);

					// String sport_name = JsonObject.getString("ss_sport");

					String player1 = JsonObject.getString("player1");
					String player2 = JsonObject.getString("player2");
					String player3 = JsonObject.getString("player3");
					String player4 = JsonObject.getString("player4");

					String player1_country = JsonObject
							.getString("player1_country");
					String player2_country = JsonObject
							.getString("player2_country");

					String player3_country = JsonObject
							.getString("player3_country");
					String player4_country = JsonObject
							.getString("player4_country");

					String ss_player_code1 = JsonObject
							.getString("ss_player_code1");
					String ss_player_code2 = JsonObject
							.getString("ss_player_code2");
					String ss_player_code3 = JsonObject
							.getString("ss_player_code3");
					String ss_player_code4 = JsonObject
							.getString("ss_player_code4");

					String player1_club5 = JsonObject
							.getString("player1_club5");
					String player2_club5 = JsonObject
							.getString("player2_club5");

					String ss_channel_code1 = JsonObject
							.getString("channel_name1");
					String ss_channel_code2 = JsonObject
							.getString("channel_name2");
					String ss_channel_code3 = JsonObject
							.getString("channel_name3");

					String ss_match_text = JsonObject
							.getString("ss_match_text");
					String game_txt = JsonObject.getString("ss_game_text");
					
					String ss_ticket_url;
					
					if(search == true)
					{
						ss_ticket_url = "hide";
					}
					else{
						ss_ticket_url = JsonObject.getString("ss_ticket_url");
					}
					
					// .toUpperCase();

					// Log.w("suraj",""+ss_game_start);

					String ss_team_sport = JsonObject
							.getString("ss_team_sport");

					// String player_header_national_code = JsonObject
					// .getString("player_header_national_code");

					String ss_sport_code = JsonObject
							.getString("ss_sport_code");

					String ss_game_start = JsonObject
							.getString("ss_game_start");

					SimpleDateFormat formatter = new SimpleDateFormat(
							"yyyyMMddHHmmss");
					formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
					Date date = (Date) formatter.parse(ss_game_start);

					Log.e("suraj", "DA==" + date);

					SimpleDateFormat dateFormat = new SimpleDateFormat(
							"dd-MMM hh:mm a");

					String mydate = null;

					dateFormat.setTimeZone(TimeZone.getDefault());

					SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
					String myday = dayFormat.format(date).toUpperCase();
					mydate = dateFormat.format(date);

					//
					SimpleDateFormat dateFormat1 = new SimpleDateFormat(
							"dd-MM-yyyy hh:mm a");

					String mydate1 = null;

					dateFormat1.setTimeZone(TimeZone.getDefault());
					mydate1 = dateFormat1.format(date);

					SimpleDateFormat formatter1 = new SimpleDateFormat(
							"yyyyMMddHHmmss");
					formatter1.setTimeZone(TimeZone.getTimeZone("UTC"));
					Date date11 = (Date) formatter1.parse(JsonObject
							.getString("ss_game_start"));

					SimpleDateFormat dateFormat11 = new SimpleDateFormat(
							"EEE dd MMM yyyy");

					String mydate_cs = null;

					dateFormat11.setTimeZone(TimeZone.getDefault());

					SimpleDateFormat timeFormat1 = new SimpleDateFormat("hh:mm a");

					String mytime_cs = null;
					if (ss_match_text == null || ss_match_text.equals("")) {
						mytime_cs = timeFormat1.format(date11).toUpperCase();
					} else {
						mytime_cs = ss_match_text + ":  "
								+ timeFormat1.format(date11).toUpperCase();
					}

					mydate_cs = dateFormat11.format(date11);

					Bitmap channel_img1 = null;

					Bitmap channel_img2 = null;

					Bitmap channel_img3 = null;

					SimpleDateFormat formatter11 = new SimpleDateFormat(
							"yyyyMMddHHmmss");
					formatter11.setTimeZone(TimeZone.getTimeZone("UTC"));
					Date date111 = (Date) formatter11.parse(JsonObject
							.getString("ss_game_start"));

					SimpleDateFormat dateFormat111 = new SimpleDateFormat(
							"EEE dd MMM yyyy");

					String mydate11 = null;

					dateFormat111.setTimeZone(TimeZone.getDefault());

					SimpleDateFormat timeFormat11 = new SimpleDateFormat(
							"HH:mm");
					String mytime = timeFormat11.format(date111).toUpperCase();
					mydate11 = dateFormat111.format(date111);

					if (ss_team_sport.equals("A")) {

						if (champ_details == null) {
							champ_details = ss_cs_code
									+ ";"
									+ JsonObject.getString("ss_game_text")
											.toUpperCase() + ";" + "date,"
									+ mydate11 + ";" + "time,"
									+ mytime_cs + ";" + ss_channel_code1
									+ ":" + ss_channel_code2 + ":"
									+ ss_channel_code3 + ";" + mydate1;

							new_champ = JsonObject.getString("ss_game_text")
									.toUpperCase();
							new_date = mydate11;
							
							if (i == array_len - 1) {
								players.add(new Player(player1_country,
										player2_country,
										player3_country,
										player4_country, ss_sport,
										ss_cs_code, myday, mydate,
										mydate1, ss_sport_code,
										ss_cs_name, player1, player2,
										player3, player4,
										ss_player_code1,
										ss_player_code2,
										ss_player_code3,
										ss_player_code4, player1_club5,
										player2_club5, game_txt,
										ss_match_text, channel_img1,
										channel_img2, channel_img3,
										ss_channel_code1,
										ss_channel_code2,
										ss_channel_code3,
										ss_team_sport, i_foll, tablet,
										up_y_team, champ_details, null,
										null, count,ss_ticket_url));
							}
						} else {
							if (new_champ.equals(JsonObject.getString(
									"ss_game_text").toUpperCase()) == true) {
								if (new_date.equals(mydate11) == true) {
									champ_details = champ_details
											+ ";"
											+ "time,"
											+ mytime_cs;

								} else {
									new_date = mydate11;
									new_champ = JsonObject.getString(
											"ss_game_text").toUpperCase();

									champ_details = champ_details
											+ ";"
											+ "date,"
											+ mydate11
											+ ";"
											+ "time,"
											+ mytime_cs;

									if (i == array_len - 1) {
										players.add(new Player(player1_country,
												player2_country,
												player3_country,
												player4_country, ss_sport,
												ss_cs_code, myday, mydate,
												mydate1, ss_sport_code,
												ss_cs_name, player1, player2,
												player3, player4,
												ss_player_code1,
												ss_player_code2,
												ss_player_code3,
												ss_player_code4, player1_club5,
												player2_club5, game_txt,
												ss_match_text, channel_img1,
												channel_img2, channel_img3,
												ss_channel_code1,
												ss_channel_code2,
												ss_channel_code3,
												ss_team_sport, i_foll, tablet,
												up_y_team, champ_details, null,
												null, count,ss_ticket_url));
									}
								}
							} else {
								// StartActivity.champ_game_txt.add(champ_details);

								// menu_champ.add(new
								// Menu_champ_A(champ_details));

								players.add(new Player(player1_country,
										player2_country, player3_country,
										player4_country, ss_sport, ss_cs_code,
										myday, mydate, mydate1, ss_sport_code,
										ss_cs_name, player1, player2, player3,
										player4, ss_player_code1,
										ss_player_code2, ss_player_code3,
										ss_player_code4, player1_club5,
										player2_club5, game_txt, ss_match_text,
										channel_img1, channel_img2,
										channel_img3, ss_channel_code1,
										ss_channel_code2, ss_channel_code3,
										ss_team_sport, i_foll, tablet,
										up_y_team, champ_details, null, null,
										count,ss_ticket_url));

								champ_details = ss_cs_code
										+ ";"
										+ JsonObject.getString("ss_game_text")
												.toUpperCase() + ";" + "date,"
										+ mydate11 + ";" + "time,"
										+ mytime_cs + ";"
										+ ss_channel_code1 + ":"
										+ ss_channel_code2 + ":"
										+ ss_channel_code3 + ";" + mydate1;

								new_champ = JsonObject
										.getString("ss_game_text")
										.toUpperCase();
								new_date = mydate11;
								
								if (i == array_len - 1) {
									players.add(new Player(player1_country,
											player2_country,
											player3_country,
											player4_country, ss_sport,
											ss_cs_code, myday, mydate,
											mydate1, ss_sport_code,
											ss_cs_name, player1, player2,
											player3, player4,
											ss_player_code1,
											ss_player_code2,
											ss_player_code3,
											ss_player_code4, player1_club5,
											player2_club5, game_txt,
											ss_match_text, channel_img1,
											channel_img2, channel_img3,
											ss_channel_code1,
											ss_channel_code2,
											ss_channel_code3,
											ss_team_sport, i_foll, tablet,
											up_y_team, champ_details, null,
											null, count,ss_ticket_url));
								}
							}
						}
						count++;
					} else {
						players.add(new Player(player1_country,
								player2_country, player3_country,
								player4_country, ss_sport, ss_cs_code, myday,
								mydate, mydate1, ss_sport_code, ss_cs_name,
								player1, player2, player3, player4,
								ss_player_code1, ss_player_code2,
								ss_player_code3, ss_player_code4,
								player1_club5, player2_club5, game_txt,
								ss_match_text, channel_img1, channel_img2,
								channel_img3, ss_channel_code1,
								ss_channel_code2, ss_channel_code3,
								ss_team_sport, i_foll, tablet, up_y_team, null,
								mydate_cs, mytime_cs, count,ss_ticket_url));
						count++;
					}
				}

				MainActivity.playerAdaptersize = players.size();

				Log.w("Suraj_", "Players Size == "
						+ MainActivity.playerAdaptersize);

			} catch (Exception e) {
				e.printStackTrace();
			}

			// }
			// StartActivity.champ_game_txt = new ArrayList<String>();
			//
			// StartActivity.f_txt_date = new ArrayList<String>();
			//
			// StartActivity.f0_txt_match = new ArrayList<String>();

		}

		if (Utils.isNetworkAvailable(act)) {

			// new MyTask().execute(rssfeed);

		} else {
			showToast("No Network Connection!!!");
		}

	}

	@SuppressWarnings("deprecation")
	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	@SuppressLint("NewApi")
	private void addToCalendar(Context ctx, String title, String Desc,
			Long start_date_mili, long end_date_mili, String event_color) {

		Uri eventsUri, reminderuri;

		if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 14) {
			eventsUri = Uri.parse("content://com.android.calendar/events");
			reminderuri = Uri.parse("content://com.android.calendar/reminders");

			ContentValues event = new ContentValues();

			event.put(Events.CALENDAR_ID, 1);
			event.put(Events.TITLE, title);
			event.put(Events.DESCRIPTION, Desc);
			event.put(Events.DTSTART, start_date_mili);
			event.put(Events.DTEND, end_date_mili);
			event.put(Events.STATUS, 1);
			event.put(Events.EVENT_COLOR, event_color);

			event.put(Events.HAS_ALARM, 1);
			event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone
					.getDefault().getID());

			Log.v("suraj", "Event =" + TimeZone.getDefault().getID());

			Uri uri = ctx.getContentResolver().insert(
					CalendarContract.Events.CONTENT_URI, event);

			long eventID = Long.parseLong(uri.getLastPathSegment());

			ContentValues reminders = new ContentValues();
			reminders.put(Reminders.EVENT_ID, eventID);
			reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
			reminders.put(Reminders.MINUTES, 15);

			ctx.getContentResolver().insert(
					CalendarContract.Reminders.CONTENT_URI, reminders);

			Log.v("suraj", "Reminder =" + reminders);

		} else if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 8
				&& Integer.parseInt(android.os.Build.VERSION.SDK) < 14) {
			eventsUri = Uri.parse("content://com.android.calendar/events");
			reminderuri = Uri.parse("content://com.android.calendar/reminders");

			ContentValues event = new ContentValues();

			event.put(Events.CALENDAR_ID, 1);
			event.put(Events.TITLE, title);
			event.put(Events.DESCRIPTION, Desc);
			event.put(Events.DTSTART, start_date_mili);
			event.put(Events.DTEND, end_date_mili);
			event.put(Events.STATUS, 1);
			event.put(Events.HAS_ALARM, 1);
			event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone
					.getDefault().getID());

			Log.v("suraj", "Event =" + TimeZone.getDefault().getID());

			Uri uri = ctx.getContentResolver().insert(eventsUri, event);

			long eventID = Long.parseLong(uri.getLastPathSegment());

			ContentValues reminders = new ContentValues();
			reminders.put(Reminders.EVENT_ID, eventID);
			reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
			reminders.put(Reminders.MINUTES, 15);

			ctx.getContentResolver().insert(reminderuri, reminders);

			Log.v("suraj", "Reminder =" + reminders);
		}

	}

	public List<Player> getPlayers() {
		return players;
	}

	public static boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	public void showToast(String msg) {
		Toast.makeText(act, msg, Toast.LENGTH_LONG).show();
	}

}
